


#include "Sphere.h"
#include <math.h>

using namespace std;

Sphere::Sphere(double x, double y, double z, double r) {
    center.set(x, y, z);
    radius = r;
}

bool Sphere::isHit(Ray r, double tmin, double tmax, double &t) {
    double discriminate = 0.0;
    double t1, t2, dDotD, radiusSqr;
    cs5721::Vector3D negRDirection, rOrigin, rDirection, oMinusC;

    rOrigin = r.getOrigin();
    rDirection = r.getDirection();
    oMinusC = rOrigin - center;
    negRDirection = rDirection * -1.0;
    dDotD = rDirection.dot(rDirection);

    discriminate = pow(rDirection.dot(oMinusC), 2.0) - dDotD * (oMinusC.dot(oMinusC) - radiusSqr);

    if (discriminate < 0.0) {
        return false;
    } else {
        if (fabs(discriminate) < 0.00001) {
            t = (negRDirection.dot(oMinusC)) / dDotD;
            return true;
        } else {
            t1 = ((negRDirection.dot(oMinusC)) + sqrt(discriminate)) / dDotD;
            t2 = ((negRDirection.dot(oMinusC)) - sqrt(discriminate)) / dDotD;

            t = (t1 < t2) ? t1 : t2;
            return true;
        }
    }
}

